/**
 * 
 */
package com.base.server;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.HashMap;
import java.util.Map;

import com.base.model.DemoCommand;
import com.base.model.LoginUser;
import com.base.model.MessageSend;

/**
 * @author ricky
 * 
 */
public class ObjectServerHandler extends ChannelInboundHandlerAdapter {

	public static Map<Long,ChannelHandlerContext> ctxMap = new HashMap();
	
	public static Map<ChannelHandlerContext,Long> IdMap = new HashMap();
	
	@Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		System.out.println("RamoteAddress : " + ctx.channel().remoteAddress() + " active !");
		super.channelActive(ctx);
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		//System.out.println("RamoteAddress : " + ctx.channel().remoteAddress() + " msg:"+msg);
		DemoCommand command = (DemoCommand)msg;
		String action = command.getAction();
		Object obj = command.getBizObj();
		if(action.equals("login")){
			LoginUser user = (LoginUser)obj;
			ctxMap.put(user.getId(), ctx);
			IdMap.put(ctx, user.getId());
			ctx.writeAndFlush("user:"+user.getName()+" login succese");
		}else if(action.equals("sendMessage")){
			MessageSend send = (MessageSend)obj;
			ChannelHandlerContext sendCtx = ctxMap.get(send.getSendToUserId());
			if(sendCtx==null){
				ctx.writeAndFlush("send userid:"+send.getSendToUserId()+" not login");
			}else{
				sendCtx.writeAndFlush(send);
				ctx.writeAndFlush("message sendtoUserId:"+send.getSendToUserId()+" succese");
			}
		}
		
		//ctx.writeAndFlush(msg);
		//super.channelRead(ctx, msg);
	}
	
	@Override
	public void channelInactive(ChannelHandlerContext ctx) throws Exception {
		Long userId = IdMap.get(ctx);
		if(userId!=null){
			ctxMap.remove(userId);
			IdMap.remove(ctx);
			System.out.println("remove client user id:"+userId);
		}
		super.channelInactive(ctx);
	}
}
